package com.github.reweber.androidasyncsocketexamples.tcp;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.github.reweber.androidasyncsocketexamples.activity.VideoRecorderActivity;
import com.github.reweber.androidasyncsocketexamples.bean.XXXX;
import com.github.reweber.androidasyncsocketexamples.utils.Cons;
import com.github.reweber.androidasyncsocketexamples.utils.JSONUtils;
import com.koushikdutta.async.*;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.callback.DataCallback;
import com.koushikdutta.async.callback.ListenCallback;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by reweber on 12/20/14.
 */
public class Server {
    public static final String TAG = "Server";
    private InetAddress host;
    private int port;
    Handler handler;

    public Server(String host, int port, Handler handler) {
        try {
            this.host = InetAddress.getByName(host);
            this.handler = handler;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        this.port = port;

        setup();
    }

    private void setup() {
        AsyncServer.getDefault().listen(host, port, new ListenCallback() {


            @Override
            public void onAccepted(AsyncSocket socket) {

                handleAccept(socket);
            }

            @Override
            public void onListening(AsyncServerSocket socket) {

                Log.e(TAG, "开始监听连接！");
            }

            @Override
            public void onCompleted(Exception ex) {
                if (ex != null) throw new RuntimeException(ex);
                Log.e(TAG, "关闭服务");

            }
        });
    }

    String fanhui = "0";

    private void handleAccept(final AsyncSocket socket) {

        Log.e(TAG, "新的连接进来 " + socket.toString());
        Message message = new Message();
        message.what = 4;
        handler.sendMessage(message);
        socket.setDataCallback(new DataCallback() {
            @Override
            public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                byte[] allByteArray = bb.getAllByteArray();
                String name = new String(allByteArray);
                name = name.replaceAll("\r|\n", "");
                Message message = new Message();
                message.what = 1;
                message.obj = name;
                handler.sendMessage(message);
                if (VideoRecorderActivity.shedingwendu == "") {

                } else {
                    XXXX xxxx = JSONUtils.parseJSON(name, XXXX.class);
                    String w = xxxx.getW();
//                    返回
                    Integer integer1 = Integer.valueOf(w);
//设定
                    Integer integer = Integer.valueOf(VideoRecorderActivity.shedingwendu);
                    if (integer1 > integer) {
                        fanhui = "0";
                    } else {
                        fanhui = "1";
                    }
                    Util.writeAll(socket, fanhui.getBytes(), new CompletedCallback() {
                        @Override
                        public void onCompleted(Exception ex) {
                            if (ex != null) throw new RuntimeException(ex);
                            Log.e(TAG, "录制开始成功");

                        }
                    });
                }


            }
        });

        socket.setClosedCallback(new CompletedCallback() {
            @Override
            public void onCompleted(Exception ex) {
                if (ex != null) throw new RuntimeException(ex);
                Log.e(TAG, "关闭连接");
                Message message = new Message();
                message.what = 3;
                handler.sendMessage(message);
            }
        });

        socket.setEndCallback(new CompletedCallback() {
            @Override
            public void onCompleted(Exception ex) {
                if (ex != null) throw new RuntimeException(ex);
                Log.e(TAG, "[Server] Successfully end connection");

            }
        });
    }
}
